<template>
  <div class="metrics-chart">
    <div class="metrics-header">
      <el-radio-group v-model="currentMetric" size="small" @change="handleMetricChange">
        <el-radio-button v-for="metric in metrics" :key="metric.type" :value="metric.type">
          {{ metric.name }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <div id="metrics-chart" class="chart-container" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";
import { getTimeDistributionData } from "@/apis/TrafficIndicators";

// 定义指标类型
const metrics = [
  { type: "1", name: "拥堵延时指数" },
  { type: "2", name: "高延时比例" },
  { type: "3", name: "拥堵里程比" },
  { type: "4", name: "平均车速" },
  { type: "5", name: "速度偏差率" },
];

const currentMetric = ref("1");
const chart = ref<echarts.ECharts | null>(null);

// 获取Y轴配置
const getYAxisConfig = (type: string, data?: any[]) => {
  let maxValue = 0;
  if (data) {
    maxValue = Math.max(...data.map((item) => item.value));
  }
  const configs = {
    "1": { name: "拥堵延时指数", min: 1, max: (maxValue + 0.2).toFixed(2) },
    "2": { name: "高延时比例", min: 0, max: 100, axisLabel: { formatter: "{value}%" } },
    "3": {
      name: "拥堵里程比",
      min: 0,
      max: (maxValue + 1).toFixed(2),
      axisLabel: { formatter: "{value}%" },
    },
    "4": { name: "平均车速", min: 0, max: 100, axisLabel: { formatter: "{value}km/h" } },
    "5": {
      name: "速度偏差率",
      min: 0,
      max: (maxValue + 1).toFixed(2),
      axisLabel: { formatter: "{value}%" },
    },
  };
  return configs[type] || configs["1"];
};

// 初始化图表
const initChart = () => {
  nextTick(() => {
    const chartDom = document.getElementById("metrics-chart");
    if (!chartDom) return;

    chart.value = echarts.init(chartDom);
    const option = {
      tooltip: {
        show: true,
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#409EFF",
          },
          crossStyle: {
            color: "#409EFF",
          },
          lineStyle: {
            type: "dashed",
            color: "#409EFF",
          },
        },
        backgroundColor: "rgba(255, 255, 255, 0.95)",
        extraCssText: "box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);",
        borderRadius: 4,
        borderColor: "#ebeef5",
        borderWidth: 1,
        padding: [10, 15],
        textStyle: {
          color: "#606266",
        },
      },
      grid: {
        left: "3%",
        right: "3%",
        bottom: "0%",
        top: "25%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: [],
        axisLabel: {
          interval: 3,
          color: "#909399",
        },
        axisLine: {
          lineStyle: {
            color: "#DCDFE6",
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: {
        type: "value",
        ...getYAxisConfig("1"),
        splitLine: {
          lineStyle: {
            color: "#EBEEF5",
            type: "dashed",
          },
        },
        axisLabel: {
          color: "#909399",
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
      },
      series: [
        {
          name: "指标值",
          type: "line",
          smooth: true,
          data: [],
          symbolSize: 6,
          showSymbol: true,
          emphasis: {
            focus: "series",
            scale: true,
            showSymbol: true,
          },
          markArea: {
            silent: true,
            itemStyle: {
              color: "rgba(64, 158, 255, 0.1)",
            },
            data: [
              [
                {
                  name: "早高峰",
                  xAxis: "07时",
                },
                {
                  xAxis: "09时",
                },
              ],
              [
                {
                  name: "晚高峰",
                  xAxis: "17时",
                },
                {
                  xAxis: "19时",
                },
              ],
            ],
          },
          itemStyle: {
            color: "#409EFF",
            borderWidth: 2,
          },
          lineStyle: {
            width: 3,
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "rgba(64, 158, 255, 0.8)",
              },
              {
                offset: 1,
                color: "rgba(64, 158, 255, 0.1)",
              },
            ]),
            shadowColor: "rgba(64, 158, 255, 0.2)",
            shadowBlur: 10,
          },
        },
      ],
    };

    chart.value.setOption(option);
    fetchData();
  });
};

// 获取数据
const fetchData = async () => {
  try {
    const { success, data } = await getTimeDistributionData(currentMetric.value);
    if (success && chart.value) {
      chart.value.setOption({
        xAxis: {
          data: data.map((item) => item.time),
        },
        yAxis: getYAxisConfig(currentMetric.value, data),
        series: [
          {
            data: data.map((item) => item.value),
          },
        ],
      });
    }
  } catch (error) {
    console.error("获取指标数据失败:", error);
  }
};

// 处理指标切换
const handleMetricChange = () => {
  fetchData();
};

// 处理窗口大小变化
const handleResize = () => {
  nextTick(() => {
    chart.value?.resize();
  });
};

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  chart.value?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style lang="scss" scoped>
.metrics-chart {
  height: 100%;
  display: flex;
  flex-direction: column;

  .metrics-header {
    display: flex;
    justify-content: center;
  }

  .chart-container {
    flex: 1;
    min-height: 0;
  }
}
</style>
